package com.xiaochong.tir.api.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xc.logclient.utils.LogTrace;
import com.xiaochong.tir.api.component.HbaseBaseQueryComponent;
import com.xiaochong.tir.api.component.RedisCacheComponent;
import com.xiaochong.tir.api.util.ListSortUtil;
import com.xiaochong.tir.api.util.StringUtil;
import com.xiaochong.tir.common.data.Bo.CurrencyGainPriceRedisBo;
import com.xiaochong.tir.common.data.hbasepo.*;
import com.xiaochong.tir.common.data.mapper.*;
import com.xiaochong.tir.common.data.po.*;
import com.xiaochong.tir.common.data.redisPo.KActionTotalPo;
import com.xiaochong.tir.common.data.vo.*;
import com.xiaochong.tir.common.exception.hbase.HbaseCloseExcetion;
import com.xiaochong.tir.common.exception.hbase.HbaseConnectionExcetion;
import com.xiaochong.tir.common.exception.hbase.HbaseGetTableExcetion;
import com.xiaochong.tir.common.util.ApiResultCodeUtils;
import com.xiaochong.tir.common.util.DateUtils;
import com.xiaochong.tir.common.util.HbaseTableUtils;
import com.xiaochong.tir.common.util.RedisKeysUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import com.xiaochong.service.common.config.redis.RedisServer;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.MathContext;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.Semaphore;

/**
 * 此类为[基础代码]自动生成,已经拥有基本的增删改成操作 
 * <其他请自行扩展>
 * @author mengxiangdong
 * @time 2018-05-23 14:07
 *
 */
@Service
public class ImmortalsService {


    @Autowired
    private ExchangeInfoMapper exchangeInfoDao;

    @Autowired
    private ListedCompanyIndexMapper listedCompanyIndexMapper;

    @Autowired
    private NonListedCompanyIndexMapper nonListedCompanyIndexMapper;

    @Autowired
    private ConceptCategoryMapper conceptCategoryMapper;

    @Autowired
    private RedisServer redisServer;

    @Autowired
    private RedisCacheComponent redisCacheComponent;

    @Autowired
    private CurrencyInfoMapper currencyInfoMapper;

    @Autowired
    private ConceptCategoryMapper conceptCategoryMapperp;

    @Autowired
    private HbaseBaseQueryComponent hbaseBaseQueryComponent;

    @Autowired
    private CurrencyIndustryCategoryMapper currencyIndustryCategoryMapper;

    @Autowired
    private SyResearchReportMapper syResearchReportMapper;

    @Autowired
    private SyResearchReportFileMapper syResearchReportFileMapper;

    @Autowired
    private SyRotationMapMapper syRotationMapMapper;

    @Autowired
    private SyChannelsMapper syChannelsMapper;

    @Autowired
    private ExchangeInfoService exchangeInfoService;

    @Autowired
    private KLineMapper kLineMapper;

    @Autowired
    private TransactionPairMapper transactionPairMapper;

    @Autowired
    private ExchangeTransactionpairMiddleMapper exchangeTransactionpairMiddleMapper;

    @Autowired
    private KLineTradesService kLineTradesService;

    private static Semaphore semaphore = new Semaphore(1);

    @Autowired
    private ShelSelectService shelSelectService;
    @Autowired
    private SelfSelectedMapper selfSelectedMapper;
    /**
     * 货币行情
     * @return List<T>
     */
    public ApiResultVo getCurrencyQuotation(CurrencyQuotationVo currencyQuotationVo) {
        long startTime = System.currentTimeMillis();
        LogTrace.info("getCurrencyQuotation","startTime" , startTime+"");
        ApiResultVo resultVo=new ApiResultVo();
        try {
          List<CurrencyQuotationResultVo> quotationList=new ArrayList<>(  );
          List<CurrencyQuotationResultVo> quotationList2=new ArrayList<>(  );


          String CURRENCY_MARKET_All = redisServer.get( RedisKeysUtils.CURRENCY_MARKET_All );
          if(CURRENCY_MARKET_All!=null){
              LogTrace.info("货币行情", "数据来源","redis");
              quotationList =JSON.parseArray( CURRENCY_MARKET_All,CurrencyQuotationResultVo.class );
          }else {
              if (semaphore.tryAcquire(1)) {
                  try {
                      CurrencyInfo currencyInfo = new CurrencyInfo();
                      currencyInfo.setEnableFlag(true);
                      currencyInfo.setDeleteFlag(false);
                      currencyInfo.setCurrencyDiagnosisFlag(true);
                      List<CurrencyInfo> currencyList = currencyInfoMapper.selectByEntityList(currencyInfo);
                      LogTrace.info("getCurrencyQuotation", "selectByEntityList", (System.currentTimeMillis() - startTime) + "");


                      for (int i = 0; i < currencyList.size(); i++) {
                          CurrencyInfo info = currencyList.get(i);
                          long beginTime = System.currentTimeMillis();
                          LogTrace.info("getCurrencyQuotation", "getCurrencyByCmcIdBegin", info.getCmcId());
                          if (!StringUtils.isEmpty(info.getCmcId())) {
                              CurrencyQuotationResultVo currencyQuotationResultVo = getCurrencyByCmcId(info.getCmcId());
                              if (currencyQuotationResultVo != null) {
                                  quotationList.add(currencyQuotationResultVo);
                              }
                          } else {
                              LogTrace.info("getCurrencyQuotation", "getCurrencyByCmcIdIsNull", info.toString());
                          }
                          LogTrace.info("getCurrencyQuotation", "getCurrencyByCmcId", info.getCmcId() + "耗时：" + (System.currentTimeMillis() - beginTime));

                      }

                      LogTrace.info("货币行情", "数据来源", "hbase");
                      redisServer.set(RedisKeysUtils.CURRENCY_MARKET_All, JSON.toJSONString(quotationList));
                  } catch (Exception e) {
                      e.printStackTrace();
                      LogTrace.error("货币行情", e);
                  } finally {
                      semaphore.release(1);
                  }
              }
          }
//          if(semaphore.tryAcquire(1)){
//              try {
//                      CurrencyInfo currencyInfo = new CurrencyInfo();
//                      currencyInfo.setEnableFlag( true );
//                      currencyInfo.setDeleteFlag( false );
//                      currencyInfo.setCurrencyDiagnosisFlag( true );
//                      List<CurrencyInfo> currencyList = currencyInfoMapper.selectByEntityList( currencyInfo );
//                      LogTrace.info("getCurrencyQuotation","selectByEntityList" , (System.currentTimeMillis() -startTime)+"");
//                      for (int i = 0; i < currencyList.size(); i++) {
//                          CurrencyInfo info = currencyList.get( i );
//                          long beginTime = System.currentTimeMillis();
//                          LogTrace.info("getCurrencyQuotation","getCurrencyByCmcIdBegin",info.getCmcId() );
//                          if(!StringUtils.isEmpty(info.getCmcId())){
//                              CurrencyQuotationResultVo currencyQuotationResultVo = getCurrencyByCmcId( info.getCmcId() );
//                              if(currencyQuotationResultVo != null ){
//                                  quotationList.add( currencyQuotationResultVo );
//                              }
//                          }else {
//                              LogTrace.info("getCurrencyQuotation","getCurrencyByCmcIdIsNull" , info.toString());
//                          }
//                          LogTrace.info("getCurrencyQuotation","getCurrencyByCmcId" , info.getCmcId()+"耗时："+(System.currentTimeMillis()-beginTime));
//                      }
//                      LogTrace.info("货币行情", "数据来源","hbase");
//                      redisServer.set( RedisKeysUtils.CURRENCY_MARKET_All,JSON.toJSONString( quotationList ));
//              }catch (Exception e){
//                  e.printStackTrace();
//                  LogTrace.error("货币行情" ,e);
//              }finally {
//                  semaphore.release(1);
//              }
//          }else {
//              String CURRENCY_MARKET_All = redisServer.get( RedisKeysUtils.CURRENCY_MARKET_All );
//              if(CURRENCY_MARKET_All!=null){
//                  LogTrace.info("货币行情", "数据来源","redis");
//                  quotationList =JSON.parseArray( CURRENCY_MARKET_All,CurrencyQuotationResultVo.class );
//              }
//          }

            if(currencyQuotationVo.getSelectType()==null || currencyQuotationVo.getSelectType()==0){
                quotationList2=quotationList;
            }
            if(currencyQuotationVo.getSelectType()!=null){
                //币种查询
                if (currencyQuotationVo.getSelectType()==1){
                    for(int i=0;i<quotationList.size();i++){
                        CurrencyQuotationResultVo vo = quotationList.get( i );
                        String name = vo.getName();
                        if(name.contains( currencyQuotationVo.getSelectName().toUpperCase() )){
                            quotationList2.add( vo );
                        }
                    }
                }

                //交易对查询
                if (currencyQuotationVo.getSelectType()==2){
                    for(int i=0;i<quotationList.size();i++){
                        CurrencyQuotationResultVo vo = quotationList.get( i );
                        String name = vo.getTransactionName();
                        if(name!=null){
                            if(name.contains( currencyQuotationVo.getSelectName().toUpperCase() )){
                                quotationList2.add( vo );
                            }
                        }
                    }
                }
            }

            if (quotationList2.size() == 0) {
                resultVo.setCode(ApiResultCodeUtils.SYSTEM_NULL.getCode());
                resultVo.setMessage(ApiResultCodeUtils.SYSTEM_NULL.getMsg());
                resultVo.setTradeId(LogTrace.getTrace().getTraceId());
                return resultVo;
            }

            if(StringUtils.isNotBlank( currencyQuotationVo.getField() )&&StringUtils.isNotBlank(currencyQuotationVo.getType())){
                //排序
                ListSortUtil util=new ListSortUtil();
                util.mySort( quotationList2, currencyQuotationVo.getField().trim(), currencyQuotationVo.getType().trim() );
            }

            //排名
            if (quotationList2.size()>0){
                for (int i=0;i<quotationList2.size();i++){
                    quotationList2.get( i ).setRank( i+1 );
                }
            }

            //分页
            if(currencyQuotationVo.getPageIndex()==null){
                currencyQuotationVo.setPageIndex( 1 );
            }
            if(currencyQuotationVo.getPageSize()==null){
                currencyQuotationVo.setPageSize( 15 );
            }
            LogTrace.info("getCurrencyQuotation","ALLTIME",System.currentTimeMillis()-startTime+"");
            Object result=StringUtil.pageBean(quotationList2,currencyQuotationVo.getPageIndex(),currencyQuotationVo.getPageSize()  );
            //判断每条数据是否已自选(如果用户已经登录)
            List<CurrencyQuotationResultVo> resultSelf = (List<CurrencyQuotationResultVo>) result;
            if(org.apache.commons.lang3.StringUtils.isNotBlank(currencyQuotationVo.getUserToken())){
                Integer user_id = shelSelectService.getRedisUserId(currencyQuotationVo.getUserToken());
                if(null != user_id){
                    List<Integer> middleList = new ArrayList<>();
                    for(CurrencyQuotationResultVo q:resultSelf){
                        middleList.add(Integer.valueOf(q.getId()));
                    }
                    if(middleList.size() > 0){
                        Map<String,Object> params = new HashMap<>();
                        params.put("type",2);
                        params.put("uniqueAnnotationList",middleList);
                        params.put("user_id",user_id);
                        List<SelfSelected> selfList = selfSelectedMapper.getSelfSelectByMideleId(params);
                        if(selfList != null && selfList.size()>0){
                            Map<Integer,Object> selfMap = new HashMap<>();
                            for(SelfSelected selfSelected : selfList){
                                selfMap.put(selfSelected.getUniqueAnnotation(),selfSelected.getUniqueAnnotation());
                            }
                            for(CurrencyQuotationResultVo q:resultSelf){
                                if(Integer.valueOf(q.getId()) != null && selfMap.containsKey(Integer.valueOf(q.getId()))){
                                    q.setSelfSelectFlag(1);
                                }else{
                                    q.setSelfSelectFlag(2);
                                }
                            }
                        }
                    }
                }
            }
            resultVo.setCode(ApiResultCodeUtils.BASE_SUCCESS.getCode());
            resultVo.setMessage(ApiResultCodeUtils.BASE_SUCCESS.getMsg());
            resultVo.setTradeId(LogTrace.getTrace().getTraceId());
            resultVo.setData(result);
            resultVo.setPages(currencyQuotationVo.getPageSize());
            resultVo.setTotal(quotationList2.size());
            return resultVo;
        }catch (Exception e){
            e.printStackTrace();
            LogTrace.error("货币行情",e);
            resultVo.setCode(ApiResultCodeUtils.SYSTEM_ERROR.getCode());
            resultVo.setMessage(ApiResultCodeUtils.SYSTEM_ERROR.getMsg());
            resultVo.setTradeId(LogTrace.getTrace().getTraceId());
            return  resultVo;
        }
    }

    public CurrencyQuotationResultVo getCurrencyByCmcId(String cmcId) {
        if(StringUtils.isEmpty(cmcId)){ return null;}
        /**
         * 实时的交易所数据
         */
        return getCurrencyByCmcIdAndUserToken(cmcId);
    }
    public CurrencyQuotationResultVo getCurrencyByCmcId(String cmcId,String userToken) {
        CurrencyQuotationResultVo resultVo = getCurrencyByCmcIdAndUserToken(cmcId);
        System.out.println(JSON.toJSON( resultVo ));
        if(StringUtils.isNotBlank(userToken) && resultVo != null){
            Integer selfSelectFlag = shelSelectService.valicatSymbolSelfSelect(userToken,Integer.valueOf(resultVo.getId()),2);
            resultVo.setSelfSelectFlag(selfSelectFlag);
        }
        return resultVo;
    }

    /**
     * 根据cmcid
     * @param cmcId
     * @return
     */
    public CurrencyQuotationResultVo getCurrencyByCmcIdAndUserToken(String cmcId) {
        if(StringUtils.isEmpty(cmcId)) return null;

        String redisCacheKey =  RedisKeysUtils.CURRENCY_MARKET+cmcId;

        String result=redisServer.get( redisCacheKey);
        if (result!=null){
            LogTrace.info("getCurrencyByCmcId" , "resultKeyRedis" , redisCacheKey );
            CurrencyQuotationResultVo currencyQuotationResultVo = JSON.parseObject( result,CurrencyQuotationResultVo.class );
            return currencyQuotationResultVo;
        }

       return null;
    }

}